/*
 * Main.java
 *
 * Created on 18. květen 2007, 15:01
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package servissimulator;
import java.net.*;
import java.util.*;
import java.io.*;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
 *
 * @author jirka
 */
public class Main {
    
    private static String[] SPZ = {"AHA","ADE","BOK","CKA","BNI","OVV","OVC","AHJ","AED","ABA","1A3","3A5","1A8"};
    private static String address= "http://localhost:8000/servis/zakazky/novy/pridat/";
    private Connection connection;
    private Statement statement;
    private Random random;
    private Obec obec;
    private Jmeno jmeno;
    private Address adresa;
    
    
    /** Creates a new instance of Main 
     * @param pocet 
     */
    public Main(int pocet) {
        String line=null;
        try {
            
            Process p = Runtime.getRuntime().exec("data/rtn");
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            line = input.readLine();
            /*while ((line = input.readLine()) != null) {
                System.out.println(line);
            }*/
            input.close();
        } catch (Exception err) {
            err.printStackTrace();
        }
        
        
        obec= new Obec();
        jmeno = new Jmeno();
        adresa = new Address();
        random = new Random();
        try {
            
            Class.forName("org.postgresql.Driver");
            //vytvorime connection
            connection = DriverManager.getConnection("jdbc:postgresql://screwdriver.felk.cvut.cz:5432/mis0741","mis0741","servis");
            statement = connection.createStatement();
            int kolikrat=pocet;
            while(--kolikrat>=0){
                pridejZakazku(line,pocet-kolikrat);
                pridejZakaznika(line, pocet-kolikrat);
            }
            //todo ... all operations
            connection.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    private void pridejZakazku(String PID, int cislo) {
        try {
            
            Statement statement1 = connection.createStatement();
            ResultSet rSet = statement1.executeQuery("select max(id) from servis_zakaznik");
            rSet.next();
            int zakaznik_max = rSet.getInt(1);
            
            rSet = statement1.executeQuery("select max(id) from servis_sazebnik");
            rSet.next();
            int sazebnik_max = rSet.getInt(1);
            
            java.lang.String data=null;
            try     {
                int pocetSelectuUkony = random.nextInt(sazebnik_max)+1;
                String spz = SPZ[random.nextInt(SPZ.length)];
                spz = spz+" "+random.nextInt(99)+" "+random.nextInt(99);
                String ukony =(new Integer(pocetSelectuUkony)).toString();
                String zakaznik_id = (new java.lang.Integer(random.nextInt(zakaznik_max))).toString();
                
                data = java.net.URLEncoder.encode("pocetSelectuUkony",  "UTF-8") + "=" + java.net.URLEncoder.encode(ukony, "UTF-8");
                
                data += "&" + java.net.URLEncoder.encode("zakaznik_id", "UTF-8") +  "=" + java.net.URLEncoder.encode(zakaznik_id,   "UTF-8");
                
                data += "&" + java.net.URLEncoder.encode("pocetSelectuSoubory", "UTF-8") + "=" +java.net.URLEncoder.encode("-1", "UTF-8");
                data += "&" + java.net.URLEncoder.encode("spz", "UTF-8") + "=" + java.net.URLEncoder.encode(spz, "UTF-8");
                data += "&" + java.net.URLEncoder.encode("popis", "UTF-8") + "=" + java.net.URLEncoder.encode("Lorem Ipsum", "UTF-8");
                for(int i=1; i<=pocetSelectuUkony; i++){
                    data += "&" + java.net.URLEncoder.encode((new Integer(i)).toString(), "UTF-8") + "="
                            + java.net.URLEncoder.encode((new Integer(1+random.nextInt(sazebnik_max))).toString(), "UTF-8");
                }
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger("global").log(Level.SEVERE, null, ex);
            }
            
            // System.out.println(data);
            // Send data
            URL url = new URL(address);
            
            URLConnection conn = url.openConnection();
            
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();
            
            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                // System.out.println(line);
            }
            System.out.println(PID+"  Uspesne pridani zakazky "+cislo);
            wr.close();
            rd.close();
            statement1.close();
        } catch (MalformedURLException ex) {
            Logger.getLogger("global").log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            //Logger.getLogger("global").log(Level.SEVERE, null, ex);
            System.out.println(PID+" Neuspesne pridani zakazky "+cislo);
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "Nepodarilo se pridat záznam!","Error",JOptionPane.ERROR_MESSAGE);
            return;
        }
        
    }
    
    
    
    
    
    
    private void pridejZakaznika(String PID, int cislo){
        try {
            // Construct data
            String data;
            if(random.nextInt(10)>6){
                data = URLEncoder.encode("jmeno", "UTF-8") + "=" + URLEncoder.encode(jmeno.getTitle()+" "+jmeno.getFirstName(), "UTF-8");
            }else{
                data = URLEncoder.encode("jmeno", "UTF-8") + "=" + URLEncoder.encode(jmeno.getFirstName(), "UTF-8");
            }
            data += "&" + URLEncoder.encode("prijmeni", "UTF-8") + "=" + URLEncoder.encode(jmeno.getLastName(), "UTF-8");
            data += "&" + URLEncoder.encode("mesto", "UTF-8") + "=" + URLEncoder.encode(obec.getRandomVillage(), "UTF-8");
            data += "&" + URLEncoder.encode("psc", "UTF-8") + "=" + URLEncoder.encode(adresa.getRandomZIPCode(), "UTF-8");
            data += "&" + URLEncoder.encode("ulice", "UTF-8") + "=" + URLEncoder.encode(adresa.getRandomStreet()+" "+random.nextInt(100), "UTF-8");
            data += "&" + URLEncoder.encode("telefon", "UTF-8") + "=" + URLEncoder.encode(jmeno.getRandomPhoneNumber(), "UTF-8");
            
            
            
            // Send data
            URL url = new URL("http://localhost:8000/servis/zakaznik/vytvoreni-zakaznika/");
            
            URLConnection conn = url.openConnection();
            
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();
            
            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                //   System.out.println(line);
            }
            System.out.println(PID+" "+" Uspesne pridani zakaznika "+cislo);
            wr.close();
            rd.close();
        } catch (Exception e) {
            System.out.println(PID+" Neuspesne pridani zakaznika "+cislo);
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        if(args.length!=1){
            System.out.println("1 argument is neccessary, it defines number of customers and orders to be added");
        }else
            // TODO code application logic here
            new Main(Integer.parseInt(args[0]));
            //new Main(2);
        // Obec o = new Obec();
        //System.out.println(o.getRandomVillage());
       /* Address a = new Address();
        System.out.println(a.getRandomStreet());
        System.out.println(a.getRandomZIPCode());*/
        /*Jmeno j = new Jmeno();
        System.out.println(j.getRandomPhoneNumber());
         * */
    }
}
